using System;
using System.Linq;
using System.Security.Claims;
using Sustainalytics.OAuth.Services.Common;
using Sustainalytics.Portfolios.BL.Model;

namespace Sustainalytics.Portfolios.Service.Controllers
{
    public interface IPortfolioUserClaimsProcessor
    {
      PortfolioUserClaims GetPortfolioClaims();
    }

    public class PortfolioUserClaimsProcessor : IPortfolioUserClaimsProcessor
    {
        public PortfolioUserClaims GetPortfolioClaims()
        {
            var userClaims = new PortfolioUserClaims();

            if (ClaimsPrincipal.Current == null || ClaimsPrincipal.Current.Claims == null)
            {
                return userClaims;
            }
            string username = ClaimsPrincipal.Current.Identity.Name;
            var userId = ClaimsPrincipal.Current.Claims.SingleOrDefault(c => c.Type == ClaimTypes.NameIdentifier).Value;
            var userGivenName = ClaimsPrincipal.Current.Claims.SingleOrDefault(c => c.Type == ClaimTypes.GivenName).Value;
            var userSurname = ClaimsPrincipal.Current.Claims.SingleOrDefault(c => c.Type == ClaimTypes.Surname).Value;
            var accountId = ClaimsPrincipal.Current.Claims.SingleOrDefault(c => c.Type == CustomClaimTypes.AccountId).Value;
            userClaims.UserFullName = userGivenName + " " + userSurname;
            userClaims.UserName = username;
            userClaims.UserId = new Guid(userId);
            userClaims.AccountId = new Guid(accountId);
            var accountUniverses = Utils.Universes.UniverseIdParser.GetAccountUniverses(ClaimsPrincipal.Current.Claims);

            userClaims.AddAccountUniverses(accountUniverses);
            return userClaims;
        }

    }
}